package net.xdclass.component;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.SmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Slf4j
@Component
public class SmsComponent {

    @Autowired
    private SmsConfig smsConfig;

    public void send(String phone, Map<String,Object> param) throws ClientException {
        if(StringUtils.isEmpty(phone)) {

        }
        //LTAI5t6EFF9XjciAxVx2TubT
        //RcPmlUDnkIZ8FiKIJuK7oflXt7Gh58
        //default 地域节点，默认就好  后面是 阿里云的 id和秘钥（这里记得去阿里云复制自己的id和秘钥哦）
        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI5t6EFF9XjciAxVx2TubT", "RcPmlUDnkIZ8FiKIJuK7oflXt7Gh58");
        IAcsClient client = new DefaultAcsClient(profile);

        //这里不能修改
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);                    //手机号
        request.putQueryParameter("SignName", "短链项目短信服务");    //申请阿里云 签名名称（暂时用阿里云测试的，自己还不能注册签名）
        request.putQueryParameter("TemplateCode", "SMS_468865752"); //申请阿里云 模板code（用的也是阿里云测试的）
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
        CommonResponse response = client.getCommonResponse(request);
        Map<String, Object> smsRes = JSON.parseObject(response.getData(), Map.class);
        if (smsRes.get("Code").equals("OK")){
            log.info("短信发送成功,响应数据:{}", response.getData());
        }else {
            log.error("短信发送失败,响应数据:{}", response.getData());
            throw new RuntimeException("短信发送失败,"+smsRes.get("Message").toString());
        }

    }
}
